package com.example.util;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.security.token.SSOToken;
import com.example.entity.LoginEntity;
import com.example.service.LoginService;
import com.example.service.RedisService;
import com.example.springs.Springs;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHelper {
    //想要在这边引入服务的几个方法，记住这种思想
    private static LoginService service;

    private static RedisService redisService;

    public static HttpServletRequest getRequest()
    {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
    }
    public static HttpServletResponse getResponse()
    {
        return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    }
    public static void setCookieUserInfo(LoginEntity entity)
    {
        SSOHelper.setCookie(getRequest(),getResponse(), SSOToken.create().setId(entity.getId()),false);
    }
    public static LoginEntity getUserInfo()
    {
        SSOToken token =SSOHelper.getSSOToken(getRequest());
        if (null==token)
            return null;//第一此登录都为null

        Long userId =Long.parseLong(token.getId());
        if (null==service)
            service= Springs.getBean(LoginService.class);
        if (null==redisService)
            redisService =Springs.getBean(RedisService.class);
        //如果是dubbo，就只能获得controller在通过其get方法得到，或者是ReferenceConfig
        if (null!=redisService.getByKey(userId.toString()))
            return (LoginEntity) redisService.getByKey(userId.toString());
        LoginEntity entity =service.getUserById(userId);
        if (null!=entity)
            redisService.setValue(entity.getId().toString(),entity);
        return entity;
    }
    public static LoginEntity getUserInfoByCache()
    {
        SSOToken token =SSOHelper.getSSOToken(getRequest());
        if (null==token)
            return null;//第一此登录都为null
        Long userId =Long.parseLong(token.getId());
        //通过redis等缓存
        return null;
    }
    public static void clearCookie()
    {
        //注销Session ：清空所有已定义的session，不只是清空全部session的值
        getRequest().getSession().invalidate();
        //清理cookie中的信息
        SSOHelper.clearLogin(getRequest(),getResponse());
    }

}
